package com.zzyl.nursing.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.interceptor.impl.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper oneMapper;

    @Autowired
    private WechatServiceImpl wechatService;
    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "权酷龙",
            "王子涛",
            "鹿哈",
            "关晓桶",
            "王二博",
            "易烊干洗",
            "黄子诚",
            "欧阳西瓜",
            "王俊卡"
    );


    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param one 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember one) {
        return oneMapper.selectFamilyMemberList(one);
    }

    /**
     * 新增老人家属
     *
     * @param one 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember one) {
        return save(one) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param one 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember one) {
        return updateById(one) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 小程序登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //根据临时code获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        //根据openid把查询到的数据封装到FamilyMember对象中
        FamilyMember familyMember = lambdaQuery().eq(FamilyMember::getOpenId, openid).one();

        //如果没有查询到，则把openid存到FamilyMember对象中，便于后续操作
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember.setOpenId(openid);
        }
        //获取到用户的手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //把对象和手机号传到方法中
        saveOrUpdateFamilyMember(familyMember, phone);

        //把对象当中的id和name传到map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", familyMember.getId());
        map.put("name", familyMember.getName());

        //生成token
        String token = tokenService.createToken(map);

        //返回token和姓名
        return LoginVo.builder().token(token).nickName(familyMember.getName()).build();

    }

    /**
     * 保存或修改客户
     *
     * @param familyMember
     * @param phone
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        // 1.判断取到的手机号与数据库当中的手机号不一致则修改手机号
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        // 2.如果对象当中存在相同的id，则修改用户信息
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            Long userId = UserThreadLocal.getUserId();
            familyMember.setCreateBy(String.valueOf(userId));
            updateById(familyMember);
            return;
        }
        // 随机组装昵称，词组+手机号后四位
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(familyMember.getPhone(), 7);

        //给familyMember对象设置昵称
        familyMember.setName(nickName);
        Long userId = UserThreadLocal.getUserId();
        familyMember.setCreateBy(String.valueOf(userId));
        save(familyMember);
    }

}
